import React, { useState, useEffect } from 'react';
import { 
  Typography, Row, Col, Card, Button, Input, Select,
  Pagination, Empty, Spin, Breadcrumb 
} from 'antd';
import { Link } from 'react-router-dom';
import { ShoppingOutlined, SearchOutlined } from '@ant-design/icons';

const { Title, Paragraph } = Typography;
const { Search } = Input;
const { Option } = Select;

// 模拟商品数据
const mockProducts = [
  {
    id: 1,
    name: 'iPhone 13 Pro',
    price: 7999,
    imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/24/wKj0iWTLe2mALDSVAAF0enjwEQA837.jpg',
    category: '电子产品',
    description: '苹果最新旗舰手机，搭载A15仿生芯片，超强性能',
    stock: 100
  },
  {
    id: 2,
    name: '华为 MateBook X Pro',
    price: 9999,
    imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/1F/wKj0iWTLSnyAINrYAAFzHRZRZtw124.jpg',
    category: '电子产品',
    description: '轻薄笔记本，高性能处理器，长续航',
    stock: 50
  },
  {
    id: 3,
    name: '小米手环7',
    price: 249,
    imageUrl: 'https://img01.71360.com/file/read/www/M00/4D/59/wKj0iGTcxUmAQwAGAAF_rOyZvxw488.jpg',
    category: '智能穿戴',
    description: '24小时心率监测，多种运动模式，防水设计',
    stock: 200
  },
  {
    id: 4,
    name: 'Sony WH-1000XM4 耳机',
    price: 2399,
    imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/A3/wKj0iWTRBW-ARRIuAAG1qClJfLY822.jpg',
    category: '电子产品',
    description: '业界领先的主动降噪，高解析度音质，长达30小时的电池续航',
    stock: 30
  },
  {
    id: 5,
    name: 'iPad Air',
    price: 4799,
    imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/23/wKj0iWTLerqAHFU8AAFoT7tZJb4297.jpg',
    category: '电子产品',
    description: '10.9英寸Liquid视网膜显示屏，A14仿生芯片',
    stock: 80
  },
  {
    id: 6,
    name: 'Switch游戏机',
    price: 2099,
    imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/24/wKj0iWTLeviAFdHhAAErLFJZZsg037.jpg',
    category: '游戏设备',
    description: '任天堂便携式游戏机，家用和掌机一体化',
    stock: 20
  },
  {
    id: 7,
    name: '戴森吹风机',
    price: 2990,
    imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/A3/wKj0iWTRBd-AQHVTAAGJk6_dB8I877.jpg',
    category: '家用电器',
    description: '智能温控，防止极端热损伤，电机数字化',
    stock: 15
  },
  {
    id: 8,
    name: 'Apple Watch Series 7',
    price: 3199,
    imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/24/wKj0iWTLevSAQ6U3AAFZZzAuwUg396.jpg',
    category: '智能穿戴',
    description: '全新屏幕设计，更大显示面积，IP6X防尘认证',
    stock: 60
  }
];

const ProductsPage: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [products, setProducts] = useState(mockProducts);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(8);
  const [total, setTotal] = useState(mockProducts.length);
  const [category, setCategory] = useState('all');
  const [sortBy, setSortBy] = useState('default');
  const [searchKeyword, setSearchKeyword] = useState('');

  useEffect(() => {
    // 模拟数据加载
    setLoading(true);
    setTimeout(() => {
      let filteredProducts = [...mockProducts];
      
      // 筛选分类
      if (category !== 'all') {
        filteredProducts = filteredProducts.filter(p => p.category === category);
      }
      
      // 搜索关键词
      if (searchKeyword) {
        filteredProducts = filteredProducts.filter(p => 
          p.name.toLowerCase().includes(searchKeyword.toLowerCase()) || 
          p.description.toLowerCase().includes(searchKeyword.toLowerCase())
        );
      }
      
      // 排序
      if (sortBy === 'price-asc') {
        filteredProducts.sort((a, b) => a.price - b.price);
      } else if (sortBy === 'price-desc') {
        filteredProducts.sort((a, b) => b.price - a.price);
      }
      
      setProducts(filteredProducts);
      setTotal(filteredProducts.length);
      setLoading(false);
    }, 500);
  }, [category, sortBy, searchKeyword]);

  const handleCategoryChange = (value: string) => {
    setCategory(value);
    setCurrentPage(1);
  };

  const handleSortChange = (value: string) => {
    setSortBy(value);
  };

  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setCurrentPage(1);
  };

  const handlePageChange = (page: number, pageSize: number) => {
    setCurrentPage(page);
    setPageSize(pageSize);
  };

  const startIndex = (currentPage - 1) * pageSize;
  const displayProducts = products.slice(startIndex, startIndex + pageSize);

  return (
    <div className="products-page">
      <Breadcrumb style={{ marginBottom: 16 }}>
        <Breadcrumb.Item>
          <Link to="/">首页</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>商品列表</Breadcrumb.Item>
      </Breadcrumb>
      
      <Title level={2}>
        <ShoppingOutlined /> 商品列表
      </Title>
      <Paragraph>探索我们的精选商品，品质保证！</Paragraph>
      
      <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: '12px' }}>
        <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
          <Select
            defaultValue="all"
            style={{ width: 120 }}
            onChange={handleCategoryChange}
          >
            <Option value="all">全部分类</Option>
            <Option value="电子产品">电子产品</Option>
            <Option value="智能穿戴">智能穿戴</Option>
            <Option value="家用电器">家用电器</Option>
            <Option value="游戏设备">游戏设备</Option>
          </Select>
          
          <Select
            defaultValue="default"
            style={{ width: 120 }}
            onChange={handleSortChange}
          >
            <Option value="default">默认排序</Option>
            <Option value="price-asc">价格从低到高</Option>
            <Option value="price-desc">价格从高到低</Option>
          </Select>
        </div>
        
        <Search
          placeholder="搜索商品"
          allowClear
          onSearch={handleSearch}
          style={{ width: 250 }}
        />
      </div>
      
      {loading ? (
        <div style={{ textAlign: 'center', margin: '40px 0' }}>
          <Spin size="large" />
        </div>
      ) : (
        <>
          {displayProducts.length === 0 ? (
            <Empty description="暂无商品" />
          ) : (
            <Row gutter={[16, 16]}>
              {displayProducts.map(product => (
                <Col xs={24} sm={12} md={8} lg={6} key={product.id}>
                  <Card
                    hoverable
                    cover={<img alt={product.name} src={product.imageUrl} style={{ height: 200, objectFit: 'cover' }} />}
                  >
                    <Card.Meta
                      title={product.name}
                      description={
                        <>
                          <div style={{ color: '#ff4d4f', fontWeight: 'bold', marginBottom: 8 }}>¥{product.price}</div>
                          <div style={{ height: 40, overflow: 'hidden', textOverflow: 'ellipsis', marginBottom: 8 }}>
                            {product.description}
                          </div>
                          <div style={{ color: '#999', marginBottom: 8 }}>
                            库存: {product.stock}
                          </div>
                          <Button type="primary">
                            <Link to={`/products/${product.id}`}>查看详情</Link>
                          </Button>
                        </>
                      }
                    />
                  </Card>
                </Col>
              ))}
            </Row>
          )}
          
          <div style={{ textAlign: 'center', marginTop: 24 }}>
            <Pagination
              current={currentPage}
              pageSize={pageSize}
              total={total}
              onChange={handlePageChange}
              showSizeChanger
              showQuickJumper
            />
          </div>
        </>
      )}
    </div>
  );
};

export default ProductsPage; 